package com.ruoyi.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.system.domain.JiajiaProxyApplication;
import com.ruoyi.system.domain.JiajiaTransferAccounts;
import com.ruoyi.system.domain.JiajiaUser;
import com.ruoyi.system.domain.JiajiaWorker;
import com.ruoyi.system.domain.vo.JiajiaTransferAccountsVo;
import com.ruoyi.system.domain.vo.JiajiaUserVo;
import com.ruoyi.system.domain.vo.JiajiaWorkerVo;
import com.ruoyi.system.mapper.JiajiaUserMapper;
import com.ruoyi.system.mapper.JiajiaWorkerMapper;
import com.ruoyi.system.service.IJiajiaProxyApplicationService;
import com.ruoyi.system.service.IJiajiaTransferAccountsService;
import com.ruoyi.system.service.IJiajiaUserService;
import com.ruoyi.system.utils.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户Service业务层处理
 *
 * @author knd
 * @date 2021-10-13
 */
@Service
public class JiajiaUserServiceImpl implements IJiajiaUserService
{
    @Autowired
    private JiajiaUserMapper jiajiaUserMapper;

    @Resource
    private JiajiaWorkerMapper jiajiaWorkerMapper;


    @Autowired
    private IJiajiaProxyApplicationService iJiajiaProxyApplicationService;
    @Resource
    private IJiajiaTransferAccountsService  iJiajiaTransferAccountsService;

    private static final Logger logger = LoggerFactory.getLogger(JiajiaUserServiceImpl.class);
    /**
     * 查询用户
     *
     * @param id 用户主键
     * @return 用户
     */
    @Override
    public JiajiaUser selectJiajiaUserById(Long id)
    {
        return jiajiaUserMapper.selectJiajiaUserById(id);
    }

    /**
     * 查询用户列表
     *
     * @param jiajiaUser 用户
     * @return 用户
     */
    @Override
    public List<JiajiaUser> selectJiajiaUserList(JiajiaUser jiajiaUser)
    {
        return jiajiaUserMapper.selectJiajiaUserList(jiajiaUser);
    }

    /**
     * 新增用户
     *
     * @param jiajiaUser 用户
     * @return 结果
     */
    @Override
    public int insertJiajiaUser(JiajiaUser jiajiaUser)
    {
        return jiajiaUserMapper.insertJiajiaUser(jiajiaUser);
    }

    /**
     * 修改用户
     *
     * @param jiajiaUser 用户
     * @return 结果
     */
    @Override
    public int updateJiajiaUser(JiajiaUser jiajiaUser)
    {
        return jiajiaUserMapper.updateJiajiaUser(jiajiaUser);
    }

    /**
     * 批量删除用户
     *
     * @param ids 需要删除的用户主键
     * @return 结果
     */
    @Override
    public int deleteJiajiaUserByIds(String ids)
    {
        return jiajiaUserMapper.deleteJiajiaUserByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除用户信息
     *
     * @param id 用户主键
     * @return 结果
     */
    @Override
    public int deleteJiajiaUserById(Long id)
    {
        return jiajiaUserMapper.deleteJiajiaUserById(id);
    }

    public String getToken() {
        try {
            Map<String, Object> map = new LinkedHashMap<String, Object>();
            map.put("grant_type", "client_credential");
            map.put("appid", "wx86ad7950e07218a5");// 改成自己的appid
            map.put("secret", "50474d912f1b9e3ebcdc5605e13df955"); //改成自己的secret
            String rt = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token", map);
            JSONObject json = JSONObject.parseObject(rt);
            if (json.getString("access_token") != null || json.getString("access_token") != "") {
                System.out.println("token:" + json.getString("access_token"));
                return json.getString("access_token");
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 生成带参小程序二维码
     *
     * @param
     * @param
     * @param page
     */
    @Override
    public AjaxResult postMiniqrQr( String phone, String page) {
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(String.format("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s",getToken()));
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            JSONObject paramJson = new JSONObject();
            paramJson.put("scene", phone);
            paramJson.put("page", page);
            paramJson.put("width", 430);
            printWriter.write(paramJson.toString());
            // flush输出流的缓冲
            printWriter.flush();
            //开始获取数据

            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
            try (
                    InputStream is = httpURLConnection.getInputStream();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ) {
                byte[] buffer = new byte[1024];
                int len = -1;
                while ((len = is.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                return AjaxResult.success("操作成功",Base64.getEncoder().encodeToString(baos.toByteArray()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (httpURLConnection != null){
                httpURLConnection.disconnect();
            }
        }
        return null;
    }

    @Override
    public AjaxResult enroll() {
        Integer enroll =jiajiaUserMapper.enroll(TokenUtil.getUid());
        return AjaxResult.success(enroll);
    }

    @Override
    public JiajiaUser selectjiajiaUser(String phone) {
        JiajiaUser jiajiaUser = jiajiaUserMapper.selectjiajiaUser(phone);
        return jiajiaUser;
    }

    @Override
     public List<JiajiaUser> selectMyTeam(String phone,Integer type) {
        return jiajiaUserMapper.selectMyTeam( phone,type);
    }

    @Override
    public AjaxResult inviteUserList() {
        JiajiaUser jiajiaUser = jiajiaUserMapper.selectJiajiaUserById(TokenUtil.getUid());

        List<JiajiaUser> jiajiaUsers = jiajiaUserMapper.selectMyUser(jiajiaUser.getPhone());

        if (ObjectUtil.isEmpty(jiajiaUser)){
            return AjaxResult.error("请刷新重试");
        }
        List<JiajiaUser> jiajiaUserList = jiajiaUserMapper.inviteUserList(jiajiaUser.getPhone());
        JiajiaUserVo jiajiaUserVo = new JiajiaUserVo();
        jiajiaUserVo.setList(jiajiaUserList);
        jiajiaUserVo.setPeopleNum(Long.valueOf(jiajiaUsers.size()));
        return AjaxResult.success(jiajiaUserVo);
    }

    @Override
    public AjaxResult inviteWorkerList() {
        JiajiaUser jiajiaUser = jiajiaUserMapper.selectJiajiaUserById(TokenUtil.getUid());
        if (ObjectUtil.isEmpty(jiajiaUser)){
            return AjaxResult.error("请刷新重试");
        }
        List<JiajiaWorker> jiajiaWorker = jiajiaWorkerMapper.inviteWorkerList(jiajiaUser.getPhone());
        JiajiaWorkerVo jiajiaWorkerVo = new JiajiaWorkerVo();
        jiajiaWorkerVo.setList(jiajiaWorker);
        jiajiaWorkerVo.setPeopleNum(Long.valueOf(jiajiaWorker.size()));
        return AjaxResult.success(jiajiaWorkerVo);
    }

    @Override
    public AjaxResult inviteAgentList(Integer type) {
        JiajiaUser jiajiaUser = jiajiaUserMapper.selectJiajiaUserById(TokenUtil.getUid());
        if (ObjectUtil.isEmpty(jiajiaUser)){
            return AjaxResult.error("请刷新重试");
        }
        List<JiajiaUser> jiajiaUserList = jiajiaUserMapper.inviteAgentList(jiajiaUser.getPhone(),type);
        List<Integer> list;
        for (JiajiaUser user : jiajiaUserList) {
            List<JiajiaProxyApplication> proxyApplications = iJiajiaProxyApplicationService.selectByUserId(user.getId());
            list= proxyApplications.stream().map(JiajiaProxyApplication::getType).collect(Collectors.toList());
            user.getParams().put("type",list);
        }
        return AjaxResult.success(jiajiaUserList);
    }

    @Override
    public List<JiajiaTransferAccountsVo> confirmReceiptPayment() {
        JiajiaTransferAccounts jiajiaTransferAccounts=new JiajiaTransferAccounts();
        jiajiaTransferAccounts.setUserId(TokenUtil.getUid());
        return iJiajiaTransferAccountsService.selectJiajiaTransferAccountsList(jiajiaTransferAccounts);
    }

    @Override
    public Long select(String phone,Integer type) {
        return jiajiaUserMapper.select(phone,type);
    }

    /**
     *浓缩制查找收益人
     * @param jiajiaUser
     * @return 收益人
     */
    @Override
    public JiajiaUser selectBeneficiary(JiajiaUser jiajiaUser) {

        String inviter = jiajiaUser.getInviter();
        int count=0;//死循环保险
        while(true && count<100){
            JiajiaUser jiajiaUser1 = jiajiaUserMapper.selectjiajiaUser(inviter);
            JiajiaProxyApplication jiajiaProxyApplication=new JiajiaProxyApplication();
            jiajiaProxyApplication.setStatus(1);
            jiajiaProxyApplication.setUserId(jiajiaUser1.getId());
            List<JiajiaProxyApplication> jiajiaProxyApplications = iJiajiaProxyApplicationService.selectJiajiaProxyApplicationList(jiajiaProxyApplication);
            if(Optional.ofNullable(jiajiaProxyApplications).isPresent() && jiajiaProxyApplications.size()>0){
                return jiajiaUser1;
            }else{
                inviter=jiajiaUser1.getInviter();
            }
            count++;
        }
        logger.info("用户id为："+jiajiaUser.getId()+"未找到收益人");
        return null;
    }

}
